from socket import *
from time import ctime
import mouse_key as mk
from cStringIO import StringIO
import cPickle as pickle
import configure
# todo use stringIO replace direct read
# todo use pickle replace direct trans

BUFSIZE = 1024

RECV_ADDR = (configure.TARGET_HOST, configure.TARGET_RECV_PORT)

print RECV_ADDR

# set up target receive socket
targetRecvSocket = socket(AF_INET, SOCK_STREAM)
targetRecvSocket.bind(RECV_ADDR)
targetRecvSocket.listen(5)

while True:
    print 'waiting for connection...'
    monitorRecvSocket, addr = targetRecvSocket.accept()
    print '...connected from:', addr

    while True:
        data = monitorRecvSocket.recv(BUFSIZE)

        if data.startswith('('):
            data = data[:data.find(')') + 1]
        elif data.startswith('['):
            data = data[:data.find(']') + 1]
        pos = eval(data)
        print pos
        if len(pos) == 2:
            print 'move', pos
            mk.mouse_move(int(pos[0]), int(pos[1]))
        else:
            print 'click', pos
            mk.mouse_click(pos[0], pos[1])
    monitorRecvSocket.close()

targetRecvSocket.close()